import fetch from 'fermionjs/lib/fetch';
import pkg from '../../../package.json';
import errorCodesBuilder from '../helpers/errorCodesBuilder';
const { name } = pkg;

const errorCodes = errorCodesBuilder();

// TODO 单次发送短信数量建议不超过200
export default function sendSMS({ to, templateId, content }) {
	const {
		log,
		app: {
			config: {
				[name]: { yunpianSingleApi, yunpianApiKey },
			},
		},
	} = this;
	to = typeof to === 'string' ? to : to.join();
	const body = new URLSearchParams({
		mobile: to,
		apikey: yunpianApiKey,
		tpl_id: templateId,
		tpl_value: new URLSearchParams(content),
	}).toString();
	log.debug({ to, body }, '发送短信');

	return fetch(yunpianSingleApi, {
		body,
		method: 'POST',
		headers: {
			Accept: 'application/json;charset=utf-8',
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
		},
	})
		.then(response => {
			if (response.code !== 0) {
				throw new Error(response.msg);
			}
			return response;
		})
		.catch(err => {
			const error = errorCodes['[0E]短信发送失败'].from(err);
			log.error({ error, to, body }, error.rawMessage);
			throw error;
		});
}
